import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:xrenovation/localization/app_localizations_delegate.dart';
import 'package:xrenovation/routes.dart';
import 'package:xrenovation/services/locale_service.dart';
import 'package:xrenovation/services/theme_service.dart';
import 'package:xrenovation/utils/http.dart';
import 'package:xrenovation/utils/message_util.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 创建全局导航键
  final navigatorKey = GlobalKey<NavigatorState>();

  final localeService = LocaleService();
  final themeService = ThemeService();

  await localeService.init();
  await themeService.init();
  Http.init(navigatorKey: navigatorKey);
  MessageUtil.init(navigatorKey);

  // 设置全局错误处理
  ErrorWidget.builder = (FlutterErrorDetails details) {
    debugPrint(details.toString());
    return Container(color: Colors.white);
  };
  FlutterError.onError = (details) {
    debugPrint('Flutter error: ${details.exception}');
  };

  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: localeService),
        ChangeNotifierProvider.value(value: themeService),
        Provider.value(value: navigatorKey),
      ],
      child: const RootApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final localeService = Provider.of<LocaleService>(context);
    final themeService = Provider.of<ThemeService>(context);
    final navigatorKey = Provider.of<GlobalKey<NavigatorState>>(context);

    return GetMaterialApp(
      navigatorKey: navigatorKey,
      title: 'XRenovation',
      debugShowCheckedModeBanner: false,
      theme: themeService.lightTheme.copyWith(
        bottomSheetTheme: const BottomSheetThemeData(
          backgroundColor: Colors.white,
          modalBackgroundColor: Colors.white,
          modalBarrierColor: Colors.black54,
        ),
      ),
      darkTheme: themeService.darkTheme.copyWith(
        bottomSheetTheme: BottomSheetThemeData(
          backgroundColor: Color(0xFF121212),
          modalBackgroundColor: Color(0xFF121212),
          modalBarrierColor: Colors.black87,
        ),
      ),
      themeMode: themeService.themeMode,
      locale: localeService.locale,
      localizationsDelegates: const [
        AppLocalizationsDelegate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [Locale('en', 'US'), Locale('zh', 'CN')],
      localeResolutionCallback: (deviceLocale, supportedLocales) {
        return localeService.locale;
      },
      initialRoute: AppRoutes.home,
      onGenerateRoute: AppRoutes.generateRoute,
    );
  }
}

class RootApp extends StatelessWidget {
  const RootApp({super.key});

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Consumer2<LocaleService, ThemeService>(
        builder: (context, localeService, themeService, child) {
          return KeyedSubtree(
            key: ValueKey('locale_${localeService.locale}_theme_${themeService.themeMode}'),
            child: MaterialApp(home: MyApp()),
          );
        },
      ),
    );
  }
}
